package zerobug
{
  // Accessor for Firebug <http://www.getfirebug.com/>
  public class Console 
  {
    import flash.external.*;
    import com.adobe.serialization.json.JSON;

    public function Console():void
    {
    }

    public function log(...objects:Array):void
    {
      return applyConsole('log', objects);
    }

    public function debug(...objects:Array):void
    {
      return applyConsole('debug', objects);
    }

    public function info(...objects:Array):void
    {
      return applyConsole('info', objects);
    }

    public function warn(...objects:Array):void
    {
      return applyConsole('warn', objects);
    }

    public function assert(...objects:Array):void
    {
      return applyConsole('assert', objects);
    }

    public function dir(...objects:Array):void
    {
      return applyConsole('dir', objects);
    }

    public function time(...objects:Array):void
    {
      return applyConsole('time', objects);
    }

    public function timeEnd(...objects:Array):void
    {
      return applyConsole('timeEnd', objects);
    }

    private function applyConsole(method:String, args:Array):void
    {
      switch(method) {
      case 'log':
      case 'debug':
      case 'info':
      case 'warn':
      case 'assert':
      case 'dir':
      case 'time':
      case 'timeEnd':
        var script:String = 'console.' + method + '.apply(this, ' + JSON.encode(args) + ')';
        executeJS(script);
        break;
      default:
        throw new Error('undefined method `console.' + method + '`');
      } 
    }

    private function executeJS(script:String):void
    {
      if(ExternalInterface.available) {
        ExternalInterface.call(script);
      }
    }
  }
}
